<?php


namespace app\crm\model;

use think\facade\Db;
use app\admin\model\Common;
use app\crm\model\TransferShop;

class CustomerInfoAPI extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'customer';

    /**
     * 列表
     * @param  array $request 请求参数
     * @return array   
     */
	//EC软件中 客服修改档案的归属门店 通过接口传送档案到中台系统的 逻辑操作 2022.06.21
	public function addCustomerT(array $request): array
	{
		
		$crmId  = $request['crmId'];
		$userId = $request['userId'];
		
		//EC系统中客服的 id   2022.06.01
		$kefu_EC['17587172']=521; //凡大雪
		$kefu_EC['17587180']=522; //卢越
		$kefu_EC['17587184']=520; //曹艳春
		$kefu_EC['17587188']=525; //刘芳芳
		$kefu_EC['17587202']=523; //付一鸣
		$kefu_EC['17587206']=527; //魏李雪
		$kefu_EC['17587226']=948; //王雯雯
		$kefu_EC['17587236']=519; //马克燕 17587236
		$kefu_EC['17587240']=524; //杨玉秀 
		//$kefu_EC['17957856']=524; //凡冬冬
		
		//查询中台系统中来源的ID
		$source_type = Db::name('setting')->where('category_id','4')->column('id','name');
		//查询中台系统中疤痕类型的ID
		$scar_type = Db::name('setting')->where('category_id','1')->column('id','name');
		//查询中台系统中部位的ID
		$bw_list = Db::name('setting')->where('category_id','2')->column('id','name');
		
		//查出客户的所以信息
		$infolist = $this->setcustomerjs($crmId);
		$newInfot = json_decode($infolist['result'],true);
		
		$customertell = substr($newInfot['data'][0]['mobile'],-11) ;
		
		$res = Db::name('customer')->where('telephone','=',$customertell)->select()->toArray();
		
		if (count($res)>0) {
		   //需要 通过这个返回  到EC 给客户打标签 已经存在  
		  //标签ID : 83764797--已存在中台系统  	必填项信息不完整 --83775424  83642703--确定店面
		  $labelId = '83764797';
		  $this->addlabelinfo($crmId,$userId,$labelId);
		  exit;
		}else{
			
			$fieldInfos = $newInfot['data'][0]['fieldInfos'];
			
			foreach ($fieldInfos as $key => $val)
			{
				//获取门店ID
				if( $key == 3 && $val['81995915']!= ''&& $val['81995915']!= '营销中心'){
					$shoplist = Db::name('shop')->where('shop_name',$val['81995915'])->column('shop_id,shop_name,address,shop_phone');
					$ec_shopid = $shoplist[0]['shop_id'];
					$ec_address = $shoplist[0]['address'];
					$ec_shopname = $shoplist[0]['shop_name'];
					$ec_shopone = $shoplist[0]['shop_phone'];
					
				}
				if($key == 5){
					$scarType = $scar_type[$val['82070908']];//疤痕类型
				}
				if($key == 6){
					$bwType = $bw_list[$val['82070909']];//部位 
				}
			} 
			
			$addInfo['customer_name'] =$newInfot['data'][0]['name'] ; //客户姓名
			$addInfo['telephone'] =$customertell; //客户手机号
			$addInfo['sex'] =2; //性别 ---2是女
			$addInfo['source_id'] =$source_type[$newInfot['data'][0]['channel']]; //客户来源
			$addInfo['creator_id'] =$kefu_EC[$userId] ?? ''; //添加人
			$addInfo['operator'] =$kefu_EC[$userId] ?? ''; //添加人
			$addInfo['create_time'] = strtotime($newInfot['data'][0]['createTime']) ; //创建时间
			$addInfo['repair_progress'] =57 ; //治疗进展 
			$addInfo['remarks'] =$newInfot['data'][0]['memo'] ; //备注信息
			$addInfo['shop_id'] =$ec_shopid; //门店归属ID
			
			if($customertell!='' && $ec_shopid!='' && $scarType!='' && $bwType!=''){
			
				$inserId = Db::name('customer')->insertGetId($addInfo);
				
				if($inserId>1){
					//发送短信
					
					$senMsge = new TransferShop();
					$senMsge->sendSms($customertell,['group'=>$ec_shopname,'address'=>$ec_address,'tel'=>$ec_shopone]);
					
					
					$data =[
						'customer_setting_id_type'     => $scarType,
						'customer_setting_id_position' => $bwType,
						'customer_id'                  => $inserId
					];
					$red = Db::name('customer_scar')->insertGetId($data);
					// 存储客户的余额信息
					$customer_balanceAll = [
							[
								'shop_id'       => $ec_shopid,
								'customer_id'   => $inserId,
								'balance_category_id'   => 1,
							],[
								'shop_id'       => $ec_shopid,
								'customer_id'   => $inserId,
								'balance_category_id'   => 2,
							]
						];
					$res = Db::name('customer_balance')->where('customer_id','=',$inserId)->select()->toArray();
					if(!$res){
						Db::name('customer_balance')->insertAll($customer_balanceAll);
					}
				}
			}else{
				//必填项有数据是空值
				//标签ID : 83764797--已存在中台系统  	必填项信息不完整 --83775424
				$labelId = '83775424';
				$this->addlabelinfo($crmId,$userId,$labelId);
			}
		}
	}
	
	public function updateCustomerT(array $request): array
	{
		$customerId = $request['id'];
		$customerInfo = Db::name('customer')->where('id','=',$customerId)->column('id,customer_name,source_id,telephone,shop_id,effective_entry,operator,create_time,first_time,second_time');
	
		$kefu_EC['521']=17587172; //凡大雪
		$kefu_EC['522']=17587180; //卢越
		$kefu_EC['520']=17587184; //曹艳春
		$kefu_EC['525']=17587188; //刘芳芳
		$kefu_EC['523']=17587202; //付一鸣
		$kefu_EC['527']=17587206; //魏李雪
		$kefu_EC['948']=17587226; //王雯雯
		$kefu_EC['519']=17587236; //万川源
		$kefu_EC['524']=17587240; //杨玉秀 
		//$kefu_EC['524']=17957856; //凡冬冬
		
		$ec_kefuId = $kefu_EC[$customerInfo[0]['operator']] ?? '';//EC 中的客服ID 
		$ec_phone = $customerInfo[0]['telephone']; //EC 中的客户手机号 
		
		// 通过手机号调取 EC接口获取 客户在EC中的 客户ID
		$clientParam = $this->lookcustomerId($ec_phone);
		$clientListParam = json_decode($clientParam['result'],true);
		$crmId = $clientListParam['data'][0]['list'][0]['crmId'];
		
		$updatejdParam = $this->updateSetjindian($ec_kefuId,$crmId);
		$updatejdLiParam = json_decode($updatejdParam['result'],true);
		
		return $updatejdLiParam;
		
	} 
	
	
	/**
	 *  签名算法
	 *  该方法可以公用
	 * @param int $timeStamp
	 * @param string $appId
	 * @param string $appSecret
	 * @return string 返回签名数据
	 */
	function getSign($timeStamp, $appId, $appSecret)
	{
	    $sign = "appId={$appId}&appSecret={$appSecret}&timeStamp={$timeStamp}";
	    return strtoupper(md5($sign));
	}
	
	/**
	 * post 业务请求
	 * 该方法可以公用
	 * @param string $url
	 * @param string $jsonData
	 * @param int $cid
	 * @param string $appId
	 * @param string $appSecret
	 */
	function http_post_json($url, $jsonData, $cid, $appId, $appSecret)
	{
	    // 1. 获取当前时间戳
	    $timeStamp = time() * 1000;
	    // 2. 获取签名
	    $sign =$this-> getSign($timeStamp, $appId, $appSecret);
	    // 3. 封装请求头
	    $head = array(
	        'Content-Type: application/json; charset=utf-8',
	        'X-Ec-Cid: ' . $cid,
	        'X-Ec-Sign: ' . $sign,
	        'X-Ec-TimeStamp: ' . $timeStamp,
	        'Content-Length: ' . strlen($jsonData)
	    );
	
	    // 3. 传入http 参数
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_POST, 1);
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    // https 支持 - 对认证证书来源的检查
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	    // 请求数据放这里
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
	    // head
	    curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
	
	    // 请求服务器
	    $response = curl_exec($ch);
	    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	    curl_close($ch);
	
	    // 组织，返回结果和响应码
	    return array(
	        $httpCode,
	        $response
	    );
	}
	
	/**
	 * get 请求业务
	 * 该方法可以公用   ---get方法
	 *
	 * @param string $url
	 * @param string $jsonData
	 * @param int $cid
	 * @param string $appId
	 * @param string $appSecret
	 */
	function http_get($url, $cid, $appId, $appSecret)
	{
	    // 1. 获取当前时间戳
	    $timeStamp = time() * 1000;
	    // 2. 获取签名
	    $sign =$this-> getSign($timeStamp, $appId, $appSecret);
	    // 3. 封装请求头
	    $head = array(
	        'Content-Type: application/json; charset=utf-8',
	        'X-Ec-Cid: ' . $cid,
	        'X-Ec-Sign: ' . $sign,
	        'X-Ec-TimeStamp: ' . $timeStamp
	    );
	    // 3. 传入http 参数
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    // https 支持 - 对认证证书来源的检查
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	    // head
	    curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
	
	    // 请求服务器
	    $response = curl_exec($ch);
	    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	    curl_close($ch);
	    // 组织，返回结果和响应码
	    return array(
	        $httpCode,
	        $response
	    );
	}
	
	/**
	 * 该方法可以公用---post  方法
	 */
	function doPost($url, $jsonData)
	{
	    $cid = 16317459; // 需要换成您自己的 企业id
	    $appId = "770275123021217792"; // 需要换成您自己的 appId
	    $appSecret = "elzRSAEm75iypsL1SGy"; // 需要换成您自己的 appSecret
	    return $this->http_post_json($url, $jsonData, $cid, $appId, $appSecret);
	}
	
	/**
	 * 该方法可以公用
	 *
	 * @param string $url
	 * @param string $params
	 * @return string[]
	 */
	function doGet($url)
	{
	    $cid = 16317459; // 需要换成您自己的 企业id
	    $appId = "770275123021217792"; // 需要换成您自己的 appId
	    $appSecret = "elzRSAEm75iypsL1SGy"; // 需要换成您自己的 appSecret
	    return $this->http_get($url, $cid, $appId, $appSecret);
	}
	
	
	//通过 post 查询客户的基础信息档案---05-31
	function setcustomerjs($crmId)
	{
	    // 1. 组装请求数据
	    $data = array(
	       "crmIds"=>$crmId
	    );
	    $jsonData = json_encode($data);
	
	    // 2. 请求服务器处理
	    $url = "https://open.workec.com/v2/customer/preciseQuery";
	    list ($returnCode, $returnContent) =$this->doPost($url, $jsonData);
	
	    // 3. 输出结果：处理您的结果
	    $info['code'] = $returnCode;
	    $info['result']  = $returnContent;
		
		return $info;
	}
	//查询 自定义字段的信息
	function checkfiledparam()
	{
	    // 2. 请求服务器处理
	    $url = "https://open.workec.com/v2/config/getFieldMapping";
	    list ($returnCode, $returnContent) =$this-> doGet($url);
	   
		$info['code'] = $returnCode;
		$info['result']  = $returnContent;
		
		return $info;
		
	}
	
	//获取标签 id
	function setlabelinfo(){
		// 1. 组装请求数据
		$data = array(
		   "groupValue"=>''
		);
		$jsonData = json_encode($data);
			
		// 2. 请求服务器处理
		$url = "https://open.workec.com/v2/label/getLabelInfo";
		list ($returnCode, $returnContent) =$this->doPost($url, $jsonData);
			
		// 3. 输出结果：处理您的结果
		$info['code'] = $returnCode;
		$info['result']  = $returnContent;
		return $info;
	}
	
	//给EC系统中的客户新增标签--
	function addlabelinfo($crmId,$userId,$labelId){
		// 1. 组装请求数据
		$data = array(
		   "crmIds"=>$crmId,
		   "labels"=>$labelId,
		   "optUserId"=>$userId,
		   "type"=>0
		);
		$jsonData = json_encode($data);
			
		// 2. 请求服务器处理
		$url = "https://open.workec.com/v2/label/update";
		list ($returnCode, $returnContent) =$this->doPost($url, $jsonData);
			
		// 3. 输出结果：处理您的结果
		$info['code'] = $returnCode;
		$info['result']  = $returnContent;
		return $info;
	}
	
	//通过 客户手机号 查询客户的基础  crmid---05-31
	function lookcustomerId($tellphone)
	{
	    // 1. 组装请求数据
	    $data = array(
	       "mobile"=>$tellphone
	    );
	    $jsonData = json_encode($data);
	
	    // 2. 请求服务器处理
	    $url = "https://open.workec.com/v2/customer/queryExist";
	    list ($returnCode, $returnContent) =$this->doPost($url, $jsonData);
	
	    // 3. 输出结果：处理您的结果
	    $info['code'] = $returnCode;
	    $info['result']  = $returnContent;
		
		return $info;
	}
	//通过 客户手机号 查询客户的基础  crmid---05-31
	function updateSetjindian($ec_kefuId,$crmId)
	{
	    // 1. 组装请求数据
	    $data = array(
	       "optUserId"=>$ec_kefuId,
		   "crmId"=>$crmId,
		    "fields"=>[
			  "81995985"=>"2630724" 
			   
		   ]
	    );
		
	    $jsonData = json_encode($data);
	
	    // 2. 请求服务器处理
	    $url = "https://open.workec.com/v2/customer/updateCustomer";
	    list ($returnCode, $returnContent) =$this->doPost($url, $jsonData);
	
	    // 3. 输出结果：处理您的结果
	    $info['code'] = $returnCode;
	    $info['result']  = $returnContent;
		
		return $info;
	} 
	
}
